package com.study.controller;

import com.study.config.HadoopTemplate;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
public class HdfsController {

    @Autowired
    private HadoopTemplate hadoopTemplate;

    /**
     * 将本地文件srcFile,上传到hdfs
     *
     * @param srcFile
     * @return
     */
    @RequestMapping("/upload")
    public String upload(@RequestParam String srcFile) {
        hadoopTemplate.uploadFile(srcFile);
        return "copy";
    }

    @RequestMapping("/delFile")
    public String del(@RequestParam String fileName) {
        hadoopTemplate.delFile(fileName);
        return "delFile";
    }


    //http://192.168.134.100:8080/download?fileName=5.txt&savePath=/tmp/5.txt
    @RequestMapping("/download")
    public String download(@RequestParam String fileName, @RequestParam String savePath) {
        hadoopTemplate.download(fileName, savePath);
        return "download";
    }

    /**
     * 创建文件夹
     *http://127.0.0.1:8080/mkdir?path=test129
     * @param path
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "mkdir", method = RequestMethod.POST)
    @ResponseBody
    public String mkdir(@RequestParam("path") String path) throws Exception {
        if (StringUtils.isEmpty(path)) {
            log.debug("请求参数为空");
            return "请求参数为空";
        }
        // 创建空文件夹
        boolean isOk = hadoopTemplate.existDir(path, true);
        if (isOk) {
            log.debug("文件夹创建成功");
            return "文件夹创建成功";
        } else {
            log.debug("文件夹创建失败");
            return "文件夹创建失败";
        }
    }

    /**
     * 删除文件夹
     *
     * @param path
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "rmdir", method = RequestMethod.POST)
    @ResponseBody
    public String rmdir(@RequestParam("path") String path) throws Exception {
        if (StringUtils.isEmpty(path)) {
            log.debug("请求参数为空");
            return "请求参数为空";
        }
        // 创建空文件夹
        boolean isOk = hadoopTemplate.delDir(path);
        if (isOk) {
            log.debug("文件夹删除成功");
            return "文件夹删除成功";
        } else {
            log.debug("文件夹删除失败");
            return "文件夹删除失败";
        }
    }

}
